/**
 * 
 */
package dimensional.traveler.client.screens.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import dimensional.traveler.client.mvc.ControlledComposite;
import dimensional.traveler.client.mvc.MediatedController;
import dimensional.traveler.shared.Settings;

/**
 * @author Ender
 * 
 */
public class LoginScreen extends ControlledComposite implements ClickHandler, KeyPressHandler  {
	
	private static LoginScreenUiBinder uiBinder = GWT.create(LoginScreenUiBinder.class);
	
	interface LoginScreenUiBinder extends UiBinder<Widget, LoginScreen> {
	}
	
	@UiField
	TextBox username;
	@UiField
	PasswordTextBox password;
	@UiField
	CheckBox createUser;
	@UiField
	Button loginButton;
	@UiField
	Image logo;
	
	private LoginController controller = new LoginController();
	
	public LoginScreen() {
		initWidget(uiBinder.createAndBindUi(this));
		loginButton.addClickHandler(this);
		username.addKeyPressHandler(this);
		password.addKeyPressHandler(this);
		setBackgroundImage();
	}

	private void setBackgroundImage() {
		if (!Settings.USE_PLACEHOLDERS){
			logo.setUrl("/images/login-logo.jpg");
		}
	}
	
	@Override
	public void onClick(ClickEvent event) {
		login();
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
			login();
        }
	}

	private void login() {
		String userName = username.getText();
		String userPassword = password.getText();
		if (createUser.getValue()){
			controller.createUserAndLogin(userName, userPassword);
		} else {
			controller.login(userName, userPassword);
		}
	}

	@Override
	public MediatedController getController() {
		return controller;
	}

}
